package com.windsea.relationshipmining.services;

/**
 * Log SMS 
 */

import java.text.SimpleDateFormat;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.Looper;

import com.windsea.relationshipmining.R;
import com.windsea.relationshipmining.activity.RelationChooserActivity;
import com.windsea.relationshipmining.api.ContactApi;
import com.windsea.relationshipmining.database.DBUserData;

public class LogSMSHistory extends Service {

//	private static final String TAG = LogSMSHistory.class.getSimpleName();
	public DBUserData dbUserData;
	public MyIncomingSMSHistoryUpdater updater;
	public boolean isRunning = false;

	// Specify formatting of data and time
	SimpleDateFormat formatdatetime = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	@Override
	public void onCreate() {
		super.onCreate();

		/* Info */
		// Log.d(TAG, "LogSMSHistory created");

		/* Create Database */
		dbUserData = new DBUserData(getApplicationContext());
		updater = new MyIncomingSMSHistoryUpdater();

	}

	@SuppressWarnings("deprecation")
	@Override
	public synchronized void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		// Starting the Service is only possible if it's not already running
		if (!this.isRunning) {
			updater.start();
			this.isRunning = true;
			// Log.d(TAG, "Started LogIncomingSMSHistory");
		}

	}

	@Override
	public synchronized void onDestroy() {
		super.onDestroy();

		if (this.isRunning) {
			updater.interrupt();
			this.isRunning = false;
//			Log.d(TAG, "Destroyed LogIncomingSMSHistory");
			updater = null; // for garbage collection
			// Show notification remind user to choose relationship
			showNotification();
		}

	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	// ////// Private-Updater Thread /////////

	class MyIncomingSMSHistoryUpdater extends Thread {

		static final long DELAY = 1000; // 1s intervals between consequent sms

		@Override
		public void run() {

			boolean status = true;

			try {

				final Cursor c = getContentResolver().query(
						Uri.parse("content://sms"), null, null, null,
						"date ASC");

				// Log.d(TAG, "----------SMS Query--------------");
				// int i = 1;
				// String s = null;
				dbUserData.open();

				if (c.moveToFirst()) {

					while (!c.isAfterLast()) {
						int smsId = c.getInt(c.getColumnIndex("_id"));
						int ID = c.getInt(c.getColumnIndex("thread_id"));
						long then = c.getLong(c.getColumnIndex("date"));
						String phonenumber = ContactApi.phoneNumberProcess(c
								.getString(c.getColumnIndex("address")));
						String b = c.getString(c.getColumnIndex("body"));
						// Get Date
						String datetime = formatdatetime.format(then);
						int _type = c.getInt(c.getColumnIndex("type"));
						String type;
						// MESSAGE_TYPE_ALL = 0;
						// MESSAGE_TYPE_INBOX = 1;
						// MESSAGE_TYPE_SENT = 2;
						// MESSAGE_TYPE_DRAFT = 3;
						// MESSAGE_TYPE_OUTBOX = 4;
						// MESSAGE_TYPE_FAILED = 5; // for failed outgoing
						// messages
						// MESSAGE_TYPE_QUEUED = 6; // for messages to send
						// later
						switch (_type) {
						case 2:
							type = "Outgoing";
							break;
						case 1:
							type = "Incoming";
							break;
						default:
							type = "Unknown";
							break;

						}
						String contactID = dbUserData
								.getContactIdByPhonenumber(phonenumber);

						if (contactID != null) {
							// Store everything into database
							dbUserData.insertSMS(smsId, datetime, ID,
									contactID, b.length(), type);
							dbUserData.insertNumOfSMS(contactID, 1);
//							Thread.currentThread();
//							Thread.sleep(DELAY);

						}
						c.moveToNext(); // move to the next entry
						// i++;

					}

				}

				if (status) {
					Looper.prepare();
					status = false;
				}
				dbUserData.close();
				c.close();

			} catch (Exception e) {
				// Interrupted
				isRunning = false;
			}

			// End of SMS History Collection

			// Stop this Service //
			// Log.d(TAG, "Stopping IncomingSMS History Collection Service!");
			stopSelf();

		}
	}

	public boolean isRunning() {
		return this.isRunning;
	}

	@SuppressWarnings("deprecation")
	public void showNotification() {
		// define sound URI, the sound to be played when there's a notification

		getApplicationContext();
		NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		int icon = R.drawable.ic_launcher;
		CharSequence text = "Relationship Mining đã thu thập dữ liệu lần đầu xong";
		CharSequence contentTitle = "Relationship Mining";
		CharSequence contentText = "Nhấn vào đây để đến phần gán nhãn quan hệ của danh bạ.";
		long when = System.currentTimeMillis();

		Intent intent = new Intent(this, RelationChooserActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				intent, 0);
		Notification notification = new Notification(icon, text, when);
		long[] vibrate = { 0, 100, 200, 300 };
		notification.vibrate = vibrate;

		notification.ledARGB = Color.RED;
		notification.ledOffMS = 300;
		notification.ledOnMS = 300;

		notification.defaults |= Notification.DEFAULT_LIGHTS;
		// notification.flags |= Notification.FLAG_SHOW_LIGHTS;

		notification.setLatestEventInfo(this, contentTitle, contentText,
				contentIntent);

		notificationManager.notify(10001, notification);
	}
}